import 'package:flutter/material.dart';
import '../models/courier_company.dart';
import '../models/tracking_info.dart';
import '../services/api_service.dart';
import '../services/history_service.dart';
import '../utils/validators.dart';
import 'courier_list_screen.dart';

/// 快递查询主页面
class TrackingQueryScreen extends StatefulWidget {
  const TrackingQueryScreen({super.key});

  @override
  State<TrackingQueryScreen> createState() => _TrackingQueryScreenState();
}

class _TrackingQueryScreenState extends State<TrackingQueryScreen> {
  final _formKey = GlobalKey<FormState>();
  final _numberController = TextEditingController();
  final _phoneController = TextEditingController();
  
  CourierCompany? _selectedCourier;
  TrackingInfo? _trackingInfo;
  bool _isLoading = false;
  String? _errorMessage;

  @override
  void dispose() {
    _numberController.dispose();
    _phoneController.dispose();
    super.dispose();
  }

  Future<void> _queryTracking() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }

    setState(() {
      _isLoading = true;
      _errorMessage = null;
      _trackingInfo = null;
    });

    final response = await ApiService.queryPackage(
      number: _numberController.text.trim(),
      com: _selectedCourier?.code,
      phone: _phoneController.text.trim().isEmpty 
          ? null 
          : _phoneController.text.trim(),
    );

    setState(() {
      _isLoading = false;
      if (response.success && response.data != null) {
        _trackingInfo = response.data;
        // 保存查询历史记录
        HistoryService.addToHistory(_numberController.text.trim());
      } else {
        _errorMessage = response.message;
      }
    });
  }

  Future<void> _selectCourier() async {
    final result = await Navigator.push<CourierCompany>(
      context,
      MaterialPageRoute(
        builder: (context) => const CourierListScreen(),
      ),
    );

    if (result != null) {
      setState(() {
        _selectedCourier = result;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('快递查询'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            _buildQueryForm(),
            const SizedBox(height: 24),
            if (_isLoading) _buildLoadingWidget(),
            if (_errorMessage != null) _buildErrorWidget(),
            if (_trackingInfo != null) _buildTrackingResult(),
          ],
        ),
      ),
    );
  }

  Widget _buildQueryForm() {
    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              const Text(
                '请输入查询信息',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _numberController,
                decoration: const InputDecoration(
                  labelText: '快递单号',
                  hintText: '请输入快递单号',
                  prefixIcon: Icon(Icons.local_shipping),
                  border: OutlineInputBorder(),
                ),
                validator: Validators.validateTrackingNumber,
              ),
              const SizedBox(height: 16),
              InkWell(
                onTap: _selectCourier,
                child: InputDecorator(
                  decoration: const InputDecoration(
                    labelText: '快递公司（可选）',
                    hintText: '点击选择快递公司，默认自动识别',
                    prefixIcon: Icon(Icons.business),
                    border: OutlineInputBorder(),
                    suffixIcon: Icon(Icons.arrow_forward_ios, size: 16),
                  ),
                  child: Text(
                    _selectedCourier?.name ?? '自动识别',
                    style: TextStyle(
                      color: _selectedCourier == null 
                          ? Colors.grey[600] 
                          : Colors.black,
                    ),
                  ),
                ),
              ),
              const SizedBox(height: 16),
              TextFormField(
                controller: _phoneController,
                decoration: const InputDecoration(
                  labelText: '手机号后四位（可选）',
                  hintText: '顺丰和中通必填',
                  prefixIcon: Icon(Icons.phone),
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.number,
                maxLength: 4,
                validator: Validators.validatePhoneLastFour,
              ),
              const SizedBox(height: 16),
              ElevatedButton.icon(
                onPressed: _isLoading ? null : _queryTracking,
                icon: const Icon(Icons.search),
                label: const Text('查询物流'),
                style: ElevatedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  textStyle: const TextStyle(fontSize: 16),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildLoadingWidget() {
    return const Center(
      child: Padding(
        padding: EdgeInsets.all(32),
        child: CircularProgressIndicator(),
      ),
    );
  }

  Widget _buildErrorWidget() {
    return Card(
      color: Colors.red[50],
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Row(
          children: [
            Icon(Icons.error_outline, color: Colors.red[700]),
            const SizedBox(width: 12),
            Expanded(
              child: Text(
                _errorMessage!,
                style: TextStyle(color: Colors.red[700]),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTrackingResult() {
    return Card(
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  _trackingInfo!.isDelivered 
                      ? Icons.check_circle 
                      : Icons.local_shipping,
                  color: _trackingInfo!.isDelivered 
                      ? Colors.green 
                      : Colors.blue,
                  size: 32,
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        _trackingInfo!.comText ?? '未知快递公司',
                        style: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        '单号: ${_trackingInfo!.nu}',
                        style: TextStyle(
                          fontSize: 14,
                          color: Colors.grey[600],
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: _trackingInfo!.isDelivered 
                    ? Colors.green[50] 
                    : Colors.blue[50],
                borderRadius: BorderRadius.circular(8),
              ),
              child: Row(
                children: [
                  Icon(
                    _trackingInfo!.isDelivered 
                        ? Icons.done_all 
                        : Icons.info_outline,
                    color: _trackingInfo!.isDelivered 
                        ? Colors.green[700] 
                        : Colors.blue[700],
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      _trackingInfo!.statusDisplay,
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                        color: _trackingInfo!.isDelivered 
                            ? Colors.green[700] 
                            : Colors.blue[700],
                      ),
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 16),
            const Text(
              '物流轨迹',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 12),
            _buildTrackingSteps(),
          ],
        ),
      ),
    );
  }

  Widget _buildTrackingSteps() {
    if (_trackingInfo!.info.isEmpty) {
      return const Padding(
        padding: EdgeInsets.all(16),
        child: Center(
          child: Text('暂无物流信息'),
        ),
      );
    }

    return ListView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: _trackingInfo!.info.length,
      itemBuilder: (context, index) {
        final step = _trackingInfo!.info[index];
        final isFirst = index == 0;
        final isLast = index == _trackingInfo!.info.length - 1;

        return IntrinsicHeight(
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                width: 60,
                child: Column(
                  children: [
                    Container(
                      width: 10,
                      height: 10,
                      decoration: BoxDecoration(
                        color: isFirst 
                            ? Theme.of(context).colorScheme.primary 
                            : Colors.grey[400],
                        shape: BoxShape.circle,
                      ),
                    ),
                    if (!isLast)
                      Expanded(
                        child: Container(
                          width: 2,
                          color: Colors.grey[300],
                        ),
                      ),
                  ],
                ),
              ),
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.only(bottom: 24),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        step.time,
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey[600],
                        ),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        step.content,
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: isFirst 
                              ? FontWeight.bold 
                              : FontWeight.normal,
                          color: isFirst 
                              ? Theme.of(context).colorScheme.primary 
                              : Colors.black87,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}

